package com.insurance.controller;

import cn.hutool.core.bean.BeanUtil;
import com.insurance.common.common.ResponseData;
import com.insurance.common.enums.CommonEnum;
import com.insurance.common.utils.JwtOperatorUtil;
import com.insurance.common.utils.SignUtil;
import com.insurance.constant.ConstantData;
import com.insurance.entity.AuthenticationUserEntity;
import com.insurance.security.InsuranceUser;
import com.insurance.service.AuthenticationUserService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 统一认证控制器
 *
 * @version 1.0
 * @date 2020/10/19
 **/
@Slf4j
@RestController
@RequestMapping("/authentication")
public class AuthenticationController {

    //region 注入类
    /**
     * 用户service
     */
    @Autowired
    private AuthenticationUserService authenticationUserService;
    //endregion

    //region 表单登录

    /**
     * 表单登录
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @PostMapping("/form/login")
    public ResponseData formLogin(@RequestParam String validateCode, @RequestParam String username,
                                  @RequestParam String password, @RequestParam Long randomCode){
        try {
            if(!ConstantData.validateCodeMap.containsKey(randomCode)){
                log.error("【[{}]登录失败, 验证码不存在】", username);
                return ResponseData.error(CommonEnum.LOGIN_VALIDATE_ERROR);
            }
            if(!ConstantData.validateCodeMap.get(randomCode).equals(validateCode)){
                log.error("【[{}]登录失败, 验证码错误】", username);
                return ResponseData.error(CommonEnum.LOGIN_VALIDATE_ERROR);
            }
            ConstantData.validateCodeMap.remove(randomCode);
            //通过用户名查询用户
            AuthenticationUserEntity user = authenticationUserService.findByUserName(username);
            if(user == null){
                log.error("【[{}]登录失败, 用户不存在】", username);
                return ResponseData.error(CommonEnum.LOGIN_INFO_ERROR);
            }
            if(StringUtils.isBlank(user.getPassword()) || !password.equals(user.getPassword())){
                log.error("【[{}]登录失败, 用户名密码错误】", username);
                return ResponseData.error(CommonEnum.LOGIN_INFO_ERROR);
            }
            Map<String, Object> userInfoMap = BeanUtil.beanToMap(new InsuranceUser(user), false, false);
            String userToken = JwtOperatorUtil.generateToken(userInfoMap);
            log.info("【[{}]登录成功：{}】", username, userToken);
            ConstantData.tokenList.add(userToken);
            return ResponseData.success(CommonEnum.LOGIN_SUCCESS, userToken);
        } catch (Exception e) {
            log.error("【[{}]登录失败, 系统异常：{}】", username, e.getMessage());
            return ResponseData.error(CommonEnum.LOGIN_INFO_ERROR);
        }
    }
    //endregion

    //region 接口登录

    /**
     * 接口登录
     *
     * @param userName 用户名
     * @param password 密码
     * @param timeStamp 时间戳
     * @param sign 签名(两次MD5)
     * @return
     */
    @PostMapping("/interface/login")
    public ResponseData interfaceLogin(@RequestParam String userName, @RequestParam String password,
                                       @RequestParam Long timeStamp, @RequestParam String sign) {
        try {
            //验签
            if(!SignUtil.verification(userName+password+timeStamp, sign)){
                log.error("【[{}]接口登录失败, 验签错误】", userName);
                return ResponseData.error(CommonEnum.SIGN_ERROR);
            }
            //通过用户名查询用户
            AuthenticationUserEntity user = authenticationUserService.findByUserName(userName);
            if(user == null){
                log.error("【[{}]接口登录失败, 用户不存在】", userName);
                return ResponseData.error(CommonEnum.LOGIN_INFO_ERROR);
            }
            if(StringUtils.isBlank(user.getPassword()) || !password.equals(user.getPassword())){
                log.error("【[{}]接口登录失败, 用户名密码错误】", userName);
                return ResponseData.error(CommonEnum.LOGIN_INFO_ERROR);
            }
            Map<String, Object> userInfoMap = BeanUtil.beanToMap(new InsuranceUser(user), false, false);
            String userToken = JwtOperatorUtil.generateToken(userInfoMap);
            log.info("【[{}]接口登录成功：{}】", userName, userToken);
            ConstantData.tokenList.add(userToken);
            return ResponseData.success(CommonEnum.LOGIN_SUCCESS, userToken);
        } catch (Exception e) {
            log.error("【[{}]登录失败, 系统异常：{}】", userName, e.getMessage());
            return ResponseData.error(CommonEnum.LOGIN_INFO_ERROR);
        }
    }
    //endregion

    //region 登出

    /**
     * 登出
     *
     * @param request
     * @return
     */
    @PostMapping("/form/logout")
    public ResponseData formLogout(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        try {
            //获取token
            if(StringUtils.isBlank(token)){
                return ResponseData.error(CommonEnum.TOKEN_ERROR);
            }
            try {
                if(JwtOperatorUtil.isTokenExpired(token)){
                    return ResponseData.error(CommonEnum.TOKEN_ERROR);
                }
            } catch (Exception e) {
                return ResponseData.error(CommonEnum.TOKEN_ERROR);
            }
            if(ConstantData.tokenList.contains(token)){
                ConstantData.tokenList.remove(token);
            }
            return ResponseData.success(CommonEnum.LOGOUT_SUCCESS);
        } catch (Exception e) {
            log.error("【[{}]登出失败, 系统异常：{}】", token, e.getMessage());
            return ResponseData.success(CommonEnum.LOGOUT_ERROR);
        }
    }
    //endregion

    //region 获取用户信息

    /**
     * 获取用户信息
     *
     * @return
     */
    @PostMapping("/getUserInfo")
    public ResponseData getUserInfo(HttpServletRequest request){
        try {
            //获取token
            String token = request.getHeader("Authorization");
            if(StringUtils.isBlank(token)){
                return ResponseData.error(CommonEnum.TOKEN_ERROR);
            }
            //将token转换成用户信息
            Claims claims = JwtOperatorUtil.getClaimsFromToken(token);
            return ResponseData.success(claims);
        } catch (Exception e) {
            log.error("【获取用户信息失败：{}】", e.getMessage());
            return ResponseData.error(CommonEnum.TOKEN_ERROR);
        }
    }
    //endregion

    @GetMapping("/{code}/msg")
    public String msg(@PathVariable String code){
        return "msg"+code;
    }

    /*public static void main(String[] args) {
        String password = "123456";
        String userPassword = "$2a$10$lBa6qEqoS7vy6jF53Z9LVeCvuU4ClteghAwSvWBfWbqpaaF0zlCeS";
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        System.out.println(passwordEncoder.matches(password, userPassword));
    }*/


}
